package cn.wolfcode.shop.web.controller;

import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.redis.RedisService;
import cn.wolfcode.shop.redis.SeckillGoodPrefixKey;
import cn.wolfcode.shop.web.util.AccessLimit;
import cn.wolfcode.shop.web.util.VerifyCodeImgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * Created by wolfcode-lanxw
 */
@Controller
public class VerifyCodeController {
    @Autowired
    private RedisService redisService;
    @RequestMapping("/verifyCode")
    @ResponseBody
    public void getSeckillVerifyCodeImage(User user, Long goodId, HttpServletResponse response){
        if(user==null){
            return;
        }
        String verifyCodeExp = VerifyCodeImgUtil.generateVerifyCode();
        Integer result = VerifyCodeImgUtil.calc(verifyCodeExp);
        BufferedImage image = VerifyCodeImgUtil.createVerifyCodeImg(verifyCodeExp);
        redisService.set(SeckillGoodPrefixKey.SECKILL_VERIFYCODE_RESULT,user.getId()+":"+goodId,result);
        try{
            OutputStream out = response.getOutputStream();
            ImageIO.write(image,"JPEG",out);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
